<?php

class ClubController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
        $disco = new Application_Model_DbTable_Administrator();
        $this->view->disco = $disco->getAllDisco();

        /* init menu */
        require_once "models/Db/Event_db.php";
        require_once "models/Utility/Utility.php";

        $utility_handle = new Utility();
        $eventHandle    = new Event_db();

        $pivaList = $eventHandle->getAllPiva();
        foreach ($pivaList as $pivaList2){
                $piva = $pivaList2['piva'];
                $temp = $eventHandle->getUniqueNamebyPiva($piva);
                $allDisco[$piva] = array ($temp['unique_name'], $temp['name']);
        }
        $allDisco = $utility_handle->subval_sort($allDisco,0);
        $this->view->allDisco = $allDisco;
        
        foreach ($pivaList as $pivaList2){
            $piva = $pivaList2['piva'];
            $temp = $eventHandle->getPaeseDsicoByPiva($piva);
            $paese[$piva] = $temp['paese'];
            //$allDisco[] = $temp['name'];
            //$i++;
        }
        $this->view->paese = array_unique($paese);


        $categoryList = $eventHandle->getAllCategory();
        $this->view->category = $categoryList;

        $zonaList = array('Brescia','Verona','Mantova','Cremona');
        $this->view->zonaList = $zonaList;
    }

    public function indexAction()
    {
        // action body
    }

    public function showAdminInfoAction()
    {
        // action body
        $auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()) {
            $id = $auth->getIdentity()->id;
            $admin = new Application_Model_DbTable_Administrator();
            $this->view->admin = $admin->getAdmin($id);
            $this->view->club = $admin->getClub($id);
        }

    }

    public function showClubInfoAction()
    {
        // action body
        $name = $this->_getParam('name','err1');

        if ($name=="Index"){

            $this->_helper->viewRenderer->setNoRender();
            $this->_forward('eventi', 'Index');

        } else {

            $this->_helper->_layout->setLayout('layout_club');
            $piva = $this->_getParam('piva','err2');

            require_once "models/Utility/Utility.php";
            $name_disco = Utility::getUniqueDiscoName($name);
            if (!$name_disco){
                $name_disco = Utility::getUniqueDiscoName($name);
            }
            $name2=str_replace(" ", "", trim(strtolower($name_disco)));
            $name1=str_replace(" ", "", trim(strtolower($name)));
            if ($name1==$name2 && $piva=="err2"){
                    $piva = Utility::getPivaDiscoByNameUniqueDisco($name2);
            } else {
                    $piva = Utility::getPivaDiscoByNameUniqueDisco($name);
            }//end if name=name2

            require_once "models/Db/Gallery_db.php";
            $club = new Gallery_db();
            //get image for gallery: img_path & thumbh path
            $club_img = $club->getImageDataByPiva($piva);
            //get the logo image
            $logo_club = $club->getDiscoImgPath($piva);

            $discoHandler = new Application_Model_DbTable_Administrator();
            $disco = $discoHandler->getDiscoByName($name_disco);
            $this->view->disco = $disco;
            //$this->view->logo_club = $logo_club['full_path'];
            $this->view->logo_club = $logo_club;
            $this->view->name = $name_disco;
            $this->view->club_img = $club_img;

            //calcolo lat e long del club
            $paese = $disco['paese'];
            $paese2 = explode(" ",$paese);
            $paese = implode("+",$paese2);
            $address = $disco['address'];
            $address2 = explode(" ", $address);
            $address = implode("+", $address2);
            $cap = $disco['cap'];

            $geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.
                    $address .'+' . $paese . '+' . $cap . '&sensor=false');

            $output= json_decode($geocode);

            $latitude = $output->results[0]->geometry->location->lat;
            $longitude = $output->results[0]->geometry->location->lng;
            $this->view->latitude = $latitude;
            $this->view->longitude = $longitude;

            /*
             * controllo se ci sono eventi attivi per
             * questo club
             *
             */
            require_once "models/Db/Event_db.php";
            $event_handle = new Event_db();
            $event        = $event_handle->exsistActiveEvent($piva);            
            $categoria_club = $event_handle->getCategoriabyPiva($piva);

            $this->view->categoria_club = $categoria_club;            
            $this->view->event       = $event;
            $this->view->piva        = $piva;
            $unique_name  = $event_handle->getUniqueNamebyPiva($piva);
            $this->view->unique_name = $unique_name['unique_name'];
        }

    }

    public function updateClubAction()
    {
        //Check if the user is logged in
        $auth = Zend_Auth::getInstance();
            if (!$auth->hasIdentity()) {
                $nonauth="Non sei autorizzato.";
                $this->view->nonauth = $nonauth;
            } else {
            //Fetch the user's id
            //Fetch the users information
            $id = $auth->getIdentity()->id;
            $name = $this->_getParam('name','err1');
            $piva = $this->_getParam('piva','guest');

            //$this->view->piva = $piva;
        //Create the form.
            
        require_once "models/Db/Event_db.php";
        $discoDb=new Event_db();
        $discoData=$discoDb->getAllDiscoByPiva($piva);
            
        $form = $this->getUpdateForm($piva, $discoData);
        $this->view->form = $form;

        }//else isauth
    }

    public function getUpdateForm($piva, $discoData)
    {
        $form = new Zend_Form();
                
        $form->setAction('/club/success-update-club/piva/'. $piva);
        $form->setMethod('post');
        $form->setDescription("Aggiornamento Club");
        $form->setAttrib('whichclub', 'club');
        $form->addAttribs(array(
          'onSubmit' => 'editor.post()', 
        ));

        //name
        $form->addElement('text', 'name');
        $nomeElement = $form->getElement('name');
        $nomeElement->setLabel('Nome:');
        $nomeElement->setRequired(true);
        $nomeElement->setValue($discoData['name']);

        //Add validator
        $nomeElement->addValidator(
            new Zend_Validate_StringLength(4, 20)
            ); //Add Filter
        //$nomeElement->addFilter(new Zend_Filter_StringToLower());
        $nomeElement->addFilter(new Zend_Filter_StripTags());

        //address
        $form->addElement('text', 'address');
        $addressElement = $form->getElement('address');
        $addressElement->setLabel('Indirizzo:');
        $addressElement->setRequired(true);
        $addressElement->setValue($discoData['address']);

        
        //cap
        $form->addElement('text', 'cap');
        $capElement = $form->getElement('cap');
        $capElement->setLabel('CAP:');
        $capElement->setRequired(true);
        $capElement->setValue($discoData['cap']);
        
        //Add Validator
        $capElement->addValidator(
                new Zend_Validate_Digits()
                );

        //phone
    /*    $form->addElement('text', 'tel');
        $phoneElement = $form->getElement('tel');
        $phoneElement->setLabel('Phone:');
        $phoneElement->setRequired(true);
        $phoneElement->setValue($discoData['tel']);
    */

        //Add Validator
       /* $phoneElement->addValidator(
                new Zend_Validate_Digits()
                );
       */
     /*   //email address
        $form->addElement('text', 'email');
        $emailElement = $form->getElement('email');
        $emailElement->setLabel('E-mail:');
        $emailElement->setRequired(true);
        $emailElement->setValue($discoData['mail']);
     */

        //Add Validator
       /* $emailElement->addValidator(
                new Zend_Validate_EmailAddress()
                );
        //Add Filter
        $emailElement->addFilter(new Zend_Filter_StripTags());
       */
        //url
        $form->addElement('text', 'url');
        $urlElement = $form->getElement('url');
        $urlElement->setLabel('URL:');
        $urlElement->setRequired(true);
        $urlElement->setValue($discoData['url']);


        //Add Validator
       /* $urlElement->addValidator(
                new Zend_Validate_Hostname()
                );
        //Add Filter
        $urlElement->addFilter(new Zend_Filter_StripTags());
       */
        //email address
        $form->addElement('textarea', 'description');
        $descriptionElement = $form->getElement('description');
        $descriptionElement->setLabel('Descrizione del locale:');
        $descriptionElement->setRequired(true);
        $descriptionElement->setValue(html_entity_decode($discoData['description']));
        $descriptionElement->setAttrib('id', 'tagedit');

        
        //Add Filter
        //$descriptionElement->addFilter(new Zend_Filter_StripTags());

        //submit
        $form->addElement('submit', 'submit');
        $submitButton = $form->getElement('submit');
        $submitButton->setLabel('Aggiorna');

        return $form;
    }

    public function successUpdateClubAction()
    {
        // action body
        $piva = $this->_getParam('piva','guest');
        //echo "PIVA: " . $piva;
        $form=$this->getUpdateForm($piva);
        //Check if the form has been submitted.
        //If so validate and process.

            //Check if the form is valid.
            if($form->isValid($_POST)){
                //Get the values
                $name    = $form->getValue('name');
                $address = $form->getValue('address');
                $cap     = $form->getValue('cap');
                //$phone   = $form->getValue('tel');
                //$email   = $form->getValue('email');
                $phone="Notty: 3385607826 <br /> Sara: 3396741169";
                $email="info@whichclub.it";
                $url     = $form->getValue('url');
                //$piva    = $form->getValue('piva');
                $description  = $form->getValue('description');

                // use escape function
                //$name    = $this->view->escape($name);
                $address = $this->view->escape($address);
                $cap     = $this->view->escape($cap);
                $phone   = $this->view->escape($phone);
                $email   = $this->view->escape($email);
                $url     = $this->view->escape($url);
                $description  =$this->view->escape($description);
                
                $description=stripslashes($description);
                $name=stripslashes($name);

                echo "NOME: " . $name;
                //Save in db.
                $data = array( "name" => $name,
                               "address" => $address,
                               "cap" => $cap,
                               "tel" => $phone,
                               "mail" => $email,
                               "url" => $url,
                               "description" => $description );

                // db connection
                $table='disco';
                $condition='piva='.$piva;

                $admin = new Application_Model_DbTable_Administrator();
                $success = $admin->saveClub($table,$data,$condition);

                //send response to the success.phtml view
                $this->view->success = $success;

                } //Otherwise redisplay the form.
                    else{
                        $this->view->errors = $form->getMessages();
                        $this->view->form = $form;
    
    }
    
    }

    public function uploadClubImgAction()
    {
        // action body
        $auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()) {
            $id = $auth->getIdentity()->id;

            $name = $this->_getParam('name','err1');
            $piva = $this->_getParam('piva','err2');

            $form = $this->getImgUpload($name,$piva);
            $this->view->form = $form;
        } else {
            $nonauth="Non sei autorizzato.";
            $this->view->nonauth = $nonauth;
                    
    }
    
    }

    public function getImgUpload($name,$piva)
    {
        $form = new Zend_Form();
                                
//        $form->setAction('/Club/upload-succes-img/name/'.$name.'/piva/'. $piva);
        $form->setAction('/club/upload-succes-img/'.$name.'/'. $piva);
        $form->setMethod('post');
        $form->setDescription("Upload an image");

        // image upload
        $element = new Zend_Form_Element_File('image');
        $element->setLabel('Upload an image:');
        $form->addElement($element,'image');
        $element->setRequired(true);
        //Add Validator

        $form->addElement('text', 'title');
        $titleElement = $form->getElement('title');
        $titleElement->setLabel('Titolo dell\'immagine: *opzionale');
        $titleElement->addValidator(
            new Zend_Validate_StringLength(4, 20)
            ); //Add Filter
        $titleElement->addFilter(new Zend_Filter_StripTags());

        //Create description of event
        $form->addElement('textarea', 'alt');
        $descriptionElement = $form->getElement('alt');
        $descriptionElement->setLabel('Descrizione dell\'immagine: *opzionale');
        $descriptionElement->addValidator(
            new Zend_Validate_StringLength(10, 200)
            ); //Add Filter
        $descriptionElement->addFilter(new Zend_Filter_StripTags())
                           ->setAttrib('COLS', '40')
                           ->setAttrib('ROWS', '4');

        //submit
        $form->addElement('submit', 'submit');
        $submitButton = $form->getElement('submit');
        $submitButton->setLabel('Carica l\'immagine!');

        return $form;
    }

    public function uploadSuccesImgAction()
    {
        // action body
        $isError=0;
        $name = $this->_getParam('name','err1');
        $piva = $this->_getParam('piva','err2');

        $form=$this->getImgUpload($name,$piva);

        //Check if the form has been submitted.
        //If so validate and process.
            //Check if the form is valid.
            if($form->isValid($_POST)){

                $alt   = $form->getValue('alt');
                $title = $form->getValue('title');

                // uploading the image into the directory and making thumbnail
                require_once "models/Utility/Utility.php";

                if ($this->getRequest()->isPost()) {

                    $destDir = 'club_img';

                    $adapter = new Zend_File_Transfer_Adapter_Http();
                    $adapter->setDestination($destDir);
                    $adapter->addValidator('Count', false, 1)
//                            ->addValidator('IsImage', false)
                            ->addValidator('ExcludeExtension', false, array('php', 'exe', 'sql', 'gif'))
                            ->addValidator('Extension', false, 'jpg,png,jpeg,gif')
                            //->addValidator('FilesSize', false, array('min' => '0.1kB', 'max' => '200MB'))
/*                            ->addValidator('ImageSize', false, array('minwidth' => 40,
                                                                     'maxwidth' => 600,
                                                                     'minheight' => 100,
                                                                     'maxheight' => 600))
*/
                            ;

                    if ($adapter->isValid()){
                        if (!$adapter->receive()) {

                            $messages = $adapter->getMessages();
                              echo implode("\n", $messages);
                          }
                        //echo $destDir;
                        $messages = Utility::uploadImageGallery($piva, $destDir, $alt, $title);
                        $this->view->messages = $messages;
                        $this->view->name = $name;
                        $this->view->piva = $piva;
                        $this->view->isError = $isError;
                        $this->view->errors = $form->getMessages();
                   } else {
                        $isError=1;
                        $this->view->errors = $form->getMessages();
                        $this->view->form = $form;
                        $this->view->isError = $isError;
                   }
                }

                } //Otherwise redisplay the form.
                    else{
                        $isError=2;
                        $this->view->errors = $form->getMessages();
                        $this->view->form = $form;
                        $this->view->isError = $isError;
    
    }
    
    }

    public function editClubImgAction()
    {
        // action body
        // db part
        //Check if the user is logged in
        $name = $this->_getParam('name','err1');
        $piva = $this->_getParam('piva','err');
        $auth = Zend_Auth::getInstance();
            if (!$auth->hasIdentity()) {
                echo "Non sei autorizzato.";
            } else {

            require_once 'models/Db/Gallery_db.php';
            $img_obj = new Gallery_db();
            $club_img = $img_obj->getImageDataByPiva($piva);

            $this->view->piva = $piva;
            $this->view->club_img = $club_img;
                    
    }
    
    }

    public function editSuccessClubImgAction()
    {
        // action body
    }

    public function deleteClubImgAction()
    {
        // action body
        $todelete=$this->_request->getParam('img_to_delete');
        $piva = $this->_getParam('piva','err2');
        $auth = Zend_Auth::getInstance();
            if (!$auth->hasIdentity()) {
                echo "Non sei autorizzato.";

            } else {
                //print_r($todelete);
                require_once "models/Db/Gallery_db.php";
                $img_obj = new Gallery_db();
                foreach ($todelete as $todelete2){
                $err = $img_obj->deleteImageByPath($todelete2);
                if ($err == false) {
                    $success = "bad";
                    $this->view->success = $success;
                    return;
                }
                $success = "Eliminazione effettuata con successo.";
                $this->view->success = $success;
            }
        
    }
    
    }

    public function getClubImageForm($piva)
    {
        
        $form = new Zend_Form();

        $form->setAction('/club/update-success-club-image/piva/' . $piva);
        $form->setMethod('post');
        $form->setDescription("Edit image event");
        $element = new Zend_Form_Element_File('image');
        $element->setLabel('Seleziona l\'immagine:');
        $form->addElement($element, 'image');

        //submit
        $form->addElement('submit', 'submit');
        $submitButton = $form->getElement('submit');
        $submitButton->setLabel('Modifica l\'immagine!');

        return $form;
    }

    public function updateClubImageAction()
    {
        // action body
        $name = $this->_getParam('name','err1');
        $piva = $this->_getParam('piva', 'guest');
        $form=$this->getClubImageForm($piva);

        $this->view->form=$form;
    }

    public function updateSuccessClubImageAction()
    {
        // action body
        // action body

        $isErrorImg = 0; // no eror on image
        $errorImg = "";

        $id_event = $this->_getParam('piva', 'guest');
        $form=$this->getClubImageForm($id_event);

        // validating image
        $destDir = 'club_img';
        $upload = new Zend_File_Transfer_Adapter_Http();
        $upload->setDestination($destDir);
        // set the validator
        $upload->addValidator('Count', false, 1)
                ->addValidator('ExcludeExtension', false, array('php', 'exe', 'sql', 'gif'))
                ->addValidator('Extension', false, 'jpg,png,jpeg,gif');
               // ->addValidator('FilesSize', false, array('min' => '10kB', 'max' => '4MB'));

        if ($upload->isValid()){
            if ($upload->receive()) {
                $file_name = $upload->getFileName('image');
            }
            else{ // i have error on receive
                $isErrorImg=1;
                $errorImg=$upload->getMessages();
                $errorImg=implode("\n", $errorImg);
            }

            }else{ // i have error on validation
                $isErrorImg=1;
                $errorImg=$upload->getMessages();
                $errorImg=implode("\n", $errorImg);
        }


        //making thumb
        require_once "models/Utility/Utility.php";

        if($isErrorImg==0){ // no errors
        // i make the thumb

        //$admin = new Application_Model_DbTable_Administrator();

        //$data = $admin->getEventDisco('*', '*', $id_event, 0);
        $data['piva']=$id_event;


        $disco = new Application_Model_DbTable_Administrator();
        $exist=$disco->existDiscoImage($data['piva']);
        // DEBUG echo "EXIST: " . $exist  . "PIVA: " . $data['piva'];
        if($exist==0){ // i dont have the record with that piva
            // making thumbnails
            Utility::makeThumbClub($data, $file_name, $destDir,1);
        }
        else{ // the record already exist
            Utility::makeThumbClub($data, $file_name, $destDir,0);
        }

         }else{ // i have errors
            $this->view->form = $form;
         }
         
        // set the var for the view
        $this->view->isErrorImg = $isErrorImg;
        $this->view->errorImg=$errorImg;
    }

    public function array_Unchunk($array) {
        return call_User_Func_Array('array_Merge',$array);
    }
}